<?php
/*
       文件清理管理控制器
*/
namespace app\admin\controller;

use think\{Db};
use \app\base\DDL;
use \app\admin\model\Fileclear as Model;
use \app\admin\model\Syslog;

class Fileclear extends Base
{   
    public function index()
    {
		$field_list=Model::paginate(50, false, ['query' => request()->param()]);	
        $this->assign('field_list' ,$field_list);
        $this->assign('pagelist',$field_list->render());
		
		$DDL=new DDL;
		$list=$DDL->T_Get_Tables();
		foreach($list as $k=>$v){
			$list[$k]['TABLE_NAME']=$v['TABLE_NAME'];
		}
		
		$this->assign('table_list',$list);
		$this->assign('page_title','无效文件清理');
		return $this->fetch();
    }
    
	//获得指定字段
	public function get_field()
	{
		$table=input('table');
		$DDL=new DDL;
		$list=$DDL->T_Get_Fields($table,true);
		ShowJson(0,'获取成功',$list);
	}
	//获得表的信息
	public function get_table_info($table)
	{
		$dbconfig=config('database');
    	$SQL="SELECT * FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA`='".$dbconfig['database']."' AND `TABLE_NAME`='$table'";
    	$data=@db::query($SQL)[0];
    	return $data;
	}
	//获得字段的信息
	public function get_field_info($table,$field)
	{
		$dbconfig=config('database');
    	$SQL="SELECT * FROM `information_schema`.`COLUMNS` WHERE `TABLE_SCHEMA`='".$dbconfig['database']."' AND `TABLE_NAME`='$table' AND `COLUMN_NAME`='$field'";
    	$data=@db::query($SQL)[0];
    	return $data;
	}	
	//保存字段
	public function save_fields()
	{
		$data=$this->Get_Post();
		$prefix=config('database')['prefix'];
		$data['table']=str_replace($prefix,'',$data['table']);
		
		$count=Model::where("tablename",$data['table'])->where('exfield',$data['exfield'])->where('fieldname',$data['field'])->count();
		if($count>=1){
			ShowJson(1,'字段已经存在了!');
		}
		$TABLE_COMMENT=$this->get_table_info($prefix.$data['table']);
		$COLUMN_COMMENT=$this->get_field_info($prefix.$data['table'],$data['field']);
		$d=array(
			'tablename'=>$data['table'],
			'fieldname'=>$data['field'],
			'table_comment'=>$TABLE_COMMENT['TABLE_COMMENT'],
			'field_comment'=>$COLUMN_COMMENT['COLUMN_COMMENT'],
			'type'=>$data['type'],
			'exfield'=>$data['exfield']
		);
		if(Model::create($d)){
			ShowJson(0,'添加成功');
		}else{
			ShowJson(0,'添加失败');
		}
	}
	/*
		删除
	*/
	public function del()
	{
		if(Model::destroy(input('id'))){
			\ShowJson(0,'操作成功');
		}else{
			\ShowJson(1,'操作失败');
		}
	}
	public function scan_database()
	{
		/*
			1、读取待清理的数据字段
			2、字段类型，1：单文件类型  2：多文件类型  3：HTML/百度编辑器类型 4：json类型  5:序列类型
		*/
		$list=Model::select();
		$file_list=array();
		foreach($list as $data){
			if($data['type']==6){
				$result=db($data['tablename'])->field('id,'.$data['fieldname'])->where('id',$data['exfield'])->find();
				$file_list[]=$result[$data['fieldname']];
			}else{
				$slist=db($data['tablename'])->field('id,'.$data['fieldname'])->select();
				if($data['type']==1){
					foreach($slist as $v){
						$file_list[]=$v[$data['fieldname']];
					}
				}else if($data['type']==2){
					foreach($slist as $v){
						$svv=explode(',',$v[$data['fieldname']]);
						foreach($svv as $sv){
							$file_list[]=$sv;
						}
					}
				}else if($data['type']==3){
					foreach($slist as $v){
						$content=$v[$data['fieldname']];
						$preg="#src=\"/uploads(.*)\"#iUs";
						preg_match_all($preg,$content,$arr);
						if(is_array($arr[1])){
							foreach($arr[1] as $svv){
								 $file_list[]=PathDS(DS.'uploads'.$svv);
							}
						}
					}
				}else if($data['type']==4){
					
				}else if($data['type']==5){
					foreach($slist as $v){
						$sslk=unserialize($v[$data['fieldname']]);
						if(is_array($sslk)){
							foreach($sslk as $svvv){
								$file_list[]=$svvv[$data['exfield']];	
							}
						}
					}
				}	
			}
			

		}
		//整理文件列表
		$file_list=array_unique(array_values(array_filter($file_list)));
		$Upload_Dir=ROOT_PATH.'uploads';
		//扫描整个上传目录
		$list=ScandirAll($Upload_Dir);
		foreach($list as $k=>$v){
			$list[$k]=str_replace(ROOT_PATH,DS,$v);
		}
		//清理所有重复路径
		$list=array_unique(array_values($list));
		//对比出差集
		$diff=array_diff($list,$file_list);
		
		//把无效图片移动到指定目录
		$uploads_invalid=ROOT_PATH.'uploads_invalid'.DS;
		
		if(count($diff)<=0){
			ShowJson(1,'没有找到无效文件');
		}
		
		//把无效图片移动到指定目录,以恢复使用
		foreach($diff as $k=>$v){
			$file=ROOT_PATH.trim($v,'\\');
			$dsc=$uploads_invalid.Get_FileName($file);
			rename($file,$dsc);
		}
		ShowJson(0,'清理成功',count($diff));
	}
	//完全删除无效文件目录
	public function clearinvalid()
	{
		$uploads_invalid=ROOT_PATH.'uploads_invalid'.DS;
		DelFile($uploads_invalid,false);
		
		ShowJson(0,'清理完成');
	}
}
